<?php
/* ******************************
 *	Transfer aJax actions
 * ******************************
 */
 
include('../../includes/classes/core.php');

$action	= $_REQUEST['act'];
$user_id	= $_SESSION['USERID'];
$error	= '';
$data	= '';



switch ($action) {
    case 'get_add_page':
		$page		= GetPage();
		$data		= array('page'	=> $page);
		
        break;
    case 'get_edit_page':
	    $rec_id		= $_REQUEST['id'];
		$page		= GetPage(GetDescribe($rec_id));
        
        $data 		= array('page'	=> $page);
        
        break;
    case 'get_list':
	    $count = $_REQUEST['count'];
	    $hidden = $_REQUEST['hidden'];
	    
	    $rResult = mysql_query("SELECT 		`describe`.`id`,
											`describe`.`date`,
	    									`object`.`name`,
											`persons`.`name`,
    										if( `describe`.`status` = 0 , 'აქტიური', 'დასრულებული') as `status`
								FROM 		`describe`
								LEFT JOIN 	`persons` ON `describe`.`person_id` = `persons`.`id`
	    						LEFT JOIN	`object` ON `object`.`id` = `describe`.`object_id`");
		
		$data = array(
			"aaData"	=> array()
		);
		
		if(!$rResult){
			$error = 'Invalid query: ' . mysql_error();
		}else{
			while ( $aRow = mysql_fetch_array( $rResult ) )
			{
				$row = array();
				for ( $i = 0 ; $i < $count ; $i++ )
				{
					/* General output */
					$row[] = $aRow[$i];			
				}
				$data['aaData'][] = $row;
			}
			

		}
		
        break;
    case 'save_trans':
		$rec_id			= $_REQUEST['id'];
		$object_id		= $_REQUEST['ob'];
		$c_date			= date('Y-m-d H:i:s');
		$person_id		= $_REQUEST['pe'];
		$comment		= $_REQUEST['c'];
		
		AddDescribe($user_id, $rec_id, $c_date, $object_id, $person_id, $comment);
		
        break;

	case 'end_describe':
		$describe_id	= $_REQUEST['id'];
		$object_id		= $_REQUEST['ob'];
		$c_date			= date('Y-m-d H:i:s');
		$person_id		= $_REQUEST['pe'];
		$comment		= $_REQUEST['c'];
		
		checkDEscribeExists($user_id, $describe_id, $object_id, $c_date, $person_id, $comment);
		Done($describe_id, $user_id, $object_id, $c_date);

		
		break;
	case 'check_prod_list':
		$describe_id 	= $_REQUEST['id'];
		$check			= CheckProdList($describe_id);
		if($check){
			$error = 'პროდუქციის სია ცარიელია!';
		}
		
        break;
	case 'get_production_quantity':
		$production_name	= $_REQUEST['pn'];
		$object_id			= $_REQUEST['ob'];
		$data = array('quantity' => GetQuantity($production_name, $object_id));
								
		break;
    case 'get_local_id':
		$local_id = GetLocalID();
		
		$data = array('local_id' => $local_id);
        
        break;
    case 'clear_db':
		ClearDB();
		
        break;   
    default:
       $error = 'Action is Null';
}

$data['error'] = $error;

echo json_encode($data);


/* ******************************
 *	Transfer Functions
 * ******************************
 */

function ClearDB(){
	$req = mysql_query("SELECT	`id`
						FROM	`describe_detail`
						WHERE	`describe_id` NOT IN (SELECT `id` FROM `describe`)");

	while( $res = mysql_fetch_assoc($req)){
		mysql_query("DELETE
					 FROM
						`describe_detail`
					 WHERE
						`id` = '$res[id]'");
	}
}

function AddDescribe($user_id, $describe_id, $c_date, $object_id, $person_id){
	GLOBAL $error;
	$result = mysql_query("INSERT IGNORE INTO `describe` (`id`) VALUES ($describe_id)");
	if(!$result){
		$error = 'Invalid query: ' . mysql_error();
	}else{
		mysql_query("	UPDATE	`describe`
						SET
							`user_id`		= '$user_id',
							`date`			= '$c_date',
							`object_id`		= '$object_id',
							`person_id` 	= '$person_id'
						WHERE
						`id` = '$describe_id'");
	}
}

function checkDEscribeExists($user_id, $describe_id, $object_id, $c_date, $person_id){
	$result = mysql_fetch_assoc( mysql_query("	SELECT 		`describe`.`id`
												FROM 		`describe`
												WHERE	`describe`.`id` = '$describe_id'") );
	if( $result == ''){
		AddDescribe($user_id, $describe_id, $c_date, $object_id, $person_id);		
	}
	mysql_query("	UPDATE	`describe`
					SET
							`user_id`	= '$user_id',
							`status`	= 1
					WHERE	`id` = '$describe_id'");	
}

function CheckProdList($describe_id){
	$check = false;
	$req = mysql_query("SELECT	`id`
						FROM	`describe_detail`
						WHERE	`describe_id` = '$describe_id'");

	if (mysql_num_rows($req) == 0){
		$check = true;
	}

	return $check;
}

function GetLocalID(){
	GLOBAL $db;
	$local_id = $db->increment('describe');
	
	return $local_id;
}

function GetPersons($object_id){
	$data = '';
	$req = mysql_query("SELECT 	`persons`.`id`,
								`persons`.`name`
						FROM 	`persons`");
		
	while( $res = mysql_fetch_assoc($req)){			
		if($res['id'] == $object_id){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}				
	}
	return $data;
}

function GetObject($object_id){
	$data = '';
	$req = mysql_query("SELECT 	`object`.`id`,
								`object`.`name`
						FROM  	`object`
						WHERE 	`object`.`type` = 2 OR  `object`.`type` = 4 OR `object`.`type` = 6");

	while( $res = mysql_fetch_assoc($req)){
		if($res['id'] == $object_id){
			$data .= '<option value="' . $res['id'] . '" selected="selected">' . $res['name'] . '</option>';
		} else {
			$data .= '<option value="' . $res['id'] . '">' . $res['name'] . '</option>';
		}
	}
	return $data;
}


function GetDescribe($rec_id){
    $res = mysql_fetch_assoc(mysql_query("SELECT 	`id`,
    												`object_id`,
    												`person_id`,
    												`status`,
    												`comment`
									      FROM 		`describe`
									      WHERE 	`id` = '$rec_id'"));
	return $res;
}

function GetQuantity($production_name, $object_id){
	$res = mysql_fetch_assoc(mysql_query("	SELECT		IFNULL(SUM(IFNULL(`reserve`.`quantity`,1) - IFNULL(`reserve`.`sold`,1 )),0) as `quantity`
											FROM		`reserve`
											LEFT JOIN	production ON production.id	= reserve.production_id
											WHERE		`reserve`.`object_id`	= '$object_id' AND quantity-sold>0 AND (`production`.`name` ='$production_name' || `production`.`code` ='$production_name')
											"));
	return 	$res['quantity'];
}

function MakeDescribe($prod_id, $quantity, $object) {
	$req_quantity = $quantity;
	$res = mysql_query("	SELECT	`reserve`.`id`,
									`reserve`.`production_id`,
									`reserve`.`object_id`,
									`reserve`.`sold`, `price`,   `real_price`,   `vat`,
									`reserve`.`quantity` - `reserve`.`sold` AS `diff`,
									`reserve`.`create_date`
							FROM 	`reserve`
							WHERE 	`reserve`.`object_id` = '$object' && `reserve`.`production_id` = '$prod_id'
							ORDER BY `reserve`.`create_date` ASC" );

	while ( $row = mysql_fetch_array ( $res ) ) {
		if ($req_quantity > 0) {
			if ($row ['diff'] > $req_quantity) {
				$sum = $row ['sold'] + $req_quantity;
				mysql_query ( "	UPDATE `reserve`
								SET	`sold` = $sum
								WHERE	`id` = $row[id]" );
				$req_quantity = 0;
			} else if ($row ['diff'] == $req_quantity) {
					$sum = $row ['sold'] + $row ['diff'];
					mysql_query ( "UPDATE `reserve`
									SET	`sold` = $sum
									WHERE	`id` = $row[id]" );
					$req_quantity = 0;
			} else {
					$sum = $row ['sold'] + $row ['diff'];
					mysql_query ( "	UPDATE `reserve`
									SET	`sold` = $sum
									WHERE	`id` = $row[id]" );
					$req_quantity = $req_quantity - $row ['diff'];
			}
		}else {
		    if ($req_quantity<0) {

		    $sql= mysql_query("INSERT INTO `overhead` (begin_date, close_date) VALUES (NOW(), NOW())");
		     $overhead=mysql_insert_id();
		        
		    mysql_query("INSERT INTO `reserve`
		           (`object_id`, `overhead_id`, `production_id`, `quantity`,     `price`,   `real_price`,   `vat`, `create_date`)
		        VALUES
		           ($object,       $overhead,         $prod_id,     -$req_quantity, $row[price], $row[real_price], $row[vat],     NOW())");		        	
/*		    
		    mysql_query("INSERT INTO `overhead_detail`
		               (`user_id`,  `overhead_id`, `goods_id`, `name`, `quantity`,    `price`                   )
		         VALUES('$user_id', '$overhead',   '$prod_id', '',    -$req_quantity, -$req_quantity*$row[price] )");
*/		    
		    $req_quantity=0; 
		    }
		}
	}
}

function makeSale($user_id, $c_date, $object_id, $production_id, $production_quantity){
	mysql_query("	INSERT INTO `sale_transaction`
					     (`user_id`, `object_id`, `start_date`, `end_date`, `status`)
					VALUES
					     ('$user_id', '$object_id', '$c_date', '$c_date', 10)");
	
	$id = mysql_insert_id();
	
	mysql_query("	INSERT INTO `sale_transaction_detail`
					     (`user_id`, `transaction_id`, `production_id`, `product_quantity`)
					VALUES
					     ('$user_id', '$id', '$production_id', '$production_quantity')");
}

function Done($describe_id, $user_id, $object_id, $c_date){
	$res = mysql_query("SELECT 	`describe_detail`.`production_id` AS `production`,
								`describe_detail`.`quantity` - `describe_detail`.`real_quantity` AS `quantity`
						FROM  	`describe_detail`
						WHERE 	`describe_detail`.`describe_id` = '$describe_id'");
	while ($row = mysql_fetch_assoc($res)) {
		MakeDescribe($row['production'], $row['quantity'], $object_id);
		makeSale($user_id, $c_date, $object_id, $row['production'], $row['quantity']);
	}
	
	
}

function GetPage($res = ''){
	$data = '
	<!-- jQuery Dialog -->
    <div id="add-edit-prod-form" class="form-dialog" title="პროდუქტი">
    	<!-- aJax -->
	</div>
	<div id="dialog-form">
			
	    <fieldset>
	    	<legend>ძირითადი ინფორმაცია</legend>
			<table border="0" width="100%">
				<tr align="center">
					<th align="center"><label for="persom">აღმწერი პირი</label></th>
					<th align="center"><label for="object">აღმწერის ობიექტი</label></th>
				</tr>
				<tr align="center">
					<th align="center">
						<select id="person" class="idls address">' . GetPersons($res['person_id']) . '</select>
						
					</th>
					<th align="center">
						<select id="object" class="idls address">' . GetObject($res['object_id']) . '</select>
					</th>
				</tr>
				<tr>
					<th>&nbsp;</th>
				</tr>
				<tr>
					<th><label for="comment">შენიშვნა</label></th>
				</tr>									
				<tr>
					<td colspan=2>
						<textarea id="comment" class="idle large" cols="70" rows="3">' . $res['comment'] . '</textarea>
					</td>
				</tr>
			</table>
        </fieldset>

		<fieldset>
	    	<legend>პროდუქტი</legend>	
			<div id="button_area">
        		<button id="add_button1">დამატება</button><button id="del_button1">წაშლა</button>
        	</div>			
			<td>		
			    <div id="dt_example" class="ex_highlight_row">
			        <div id="container" style="width:540px;">
			            <div id="dynamic" style="overflow-x: none !important;">
			                <table class="display" id="prod_list" style="width: 580px;">
			                    <thead>
			                        <tr id="datatable_header">
			                            <th>ID</th>
			                            <th style="width: 280px !important;">პროდუქტი</th>
			                            <th style="width: 100px !important;">რაოდ.ა</th>
			                            <th style="width: 100px !important;">რეალ. რაოდ.</th>
										<th style="width: 40px !important;">#</th>
			                        </tr>
			                    </thead>
			                </table>
		                </div>
		            </div>
			    </div>
			</td>
		</fieldset>

		<input type="hidden" id="describe_id" value="' . $res['id'] . '" />
		<input type="hidden" id="describe_status" value="' . $res['status'] . '" />				
    </div>    
    ';
    
	return $data;
}
?>